package cn.bugstack.springframework.core.io;

import cn.hutool.core.util.ObjectUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author ouyangzhao
 */
public class ClassPathResource implements Resource{

    private final String path;

    private ClassLoader loader;

    public ClassPathResource(String path) {
        this(path, null);
    }



    public ClassPathResource(String path,ClassLoader loader) {
        this.path = path;
        this.loader = loader == null ? Thread.currentThread().getContextClassLoader() : loader;
    }


    @Override
    public InputStream getInputStream() throws IOException {
        InputStream resource = loader.getResourceAsStream(path);
        if(ObjectUtil.isNull(resource)){
            throw new FileNotFoundException(path + " cannot be opened because it does not exist");
        }

        return resource;
    }
}
